/* 定义全局对象，类似于命名空间或包的作用 */
var Utils = $.extend({}, Utils);

//webfunny 初始化
//if (window) {
//    let token = window.sessionStorage.getItem("SNAuthAT");
//    if (token != null) {
//        let strings = token.split("."); //截取token，获取载体
//        let userInfo = JSON.parse(decodeURIComponent(escape(window.atob(strings[1].replace(/-/g, "+").replace(/_/g, "/")))));

//        window.sessionStorage.CUSTOMER_WEB_MONITOR_ID = "webfunny_20230913_140500_dev"
//        window.localStorage.wmUserInfo = JSON.stringify({ userId: userInfo.ui, userTag: `H5—${userInfo.un}(${userInfo.coun})`, projectVersion: '1.0.1', env: 'pro' });
//    }
//}

/* 增加命名空间功能,使用方法：Utils.NameSpace('jQuery.bbb.ccc','Home.Main'); */
Utils.NameSpace = function () {
    var o = {},
        d;
    for (var i = 0; i < arguments.length; i++) {
        d = arguments[i].split('.');
        o = window[d[0]] = window[d[0]] || {};
        for (var k = 0; k < d.slice(1).length; k++) {
            o = o[d[k + 1]] = o[d[k + 1]] || {};
        }
    }
    return o;
};

Utils.host = 'https://qas.wg.ynsnjt.net';

Utils.CurDomain = {
    // 2.1网关
    //ScmSaleUrl: `http://172.10.254.68:20200/api`,
    //FeedstockUrl: `http://172.10.254.68:22000/api`,
    //PerfUrl: `http://172.10.254.68:18300/api`,
    //FiARUrl: 'http://172.10.254.68:19500/api',
    // PerfUrl: `httpa://172.10.254.68:18301/api`,
    // EmployeeMgtUrl: `https://172.10.254.68:18101/api`,
    // CarcassSaleUrl: 'https://172.10.254.68:23301/api',
    // AuxBizUrl: 'https://172.10.254.68:23101/api',
    // PartnerSvcUrl: 'https://172.10.254.68:23201/api',
    // AuditUrl: `https://172.10.254.68:21801/api`,
    //ScmInventory: `https://172.10.254.68:20301/api`,
    // SaleUrl: `https://172.39.20.70:21601/api`,
    //BaseCfgUrl: `http://172.10.254.68:21300/api`,
    //MasterDataUrl: `https://172.10.254.68:16301/api`,
    //SubDataUrl: `http://172.10.254.68:16400/api`,
    //WeiXinUrl: `https://172.10.254.68:24701/api`,
    //SysCfgUrl: `https://172.10.254.87:16201/api`,
    //SysPlfUrl: `https://172.10.254.87:15001/auth/sysplf`,
    //AccountUrl: `https://172.10.254.87:15001`,
    //EmployeeMgtUrl: `http://172.10.254.68:18100/api`,
    // FeedBackUrl: 'https://172.10.254.69:17401/api',
    // SAPSynUrl: 'https://172.10.254.68:24801/api',
    // CBSUrl: `https://172.10.254.68:21401/api`,
    // PigsltrUrl: `https://172.10.254.68:27901/api`,
    // BILivestockUrl: `https://172.10.254.68:27501/api`,
    // OtherSynUrl: `https://172.10.254.69:24901/api`,

    SaleUrl: `${Utils.host}/livestock/sale`,
    SysCfgUrl: `${Utils.host}/sysplf/syscfg`,
    BaseCfgUrl: `${Utils.host}/livestock/basecfg`,
    MasterDataUrl: `${Utils.host}/sysplf/masterdata`,
    SubDataUrl: `${Utils.host}/sysplf/subdata`,
    EmployeeMgtUrl: `${Utils.host}/hr/eplymgt`,
    SysPlfUrl: `${Utils.host}/auth/sysplf`,
    AccountUrl: `${Utils.host}`,
    WeiXinUrl: `${Utils.host}/cptvplf/weixin/mp`,
    YunZhiJiaUrl: `${Utils.host}/cptvplf/yunzhijia`,
    ShareUrl: `${Utils.host}/livestock/share`,
    CBSUrl: `${Utils.host}/livestock/cbs`,
    AuthUrl: `${Utils.host}`,
    ScmInventory: `${Utils.host}/scm/inventory`,
    JobUrl: `${Utils.host}/hr/job`,
    ScmSaleUrl: `${Utils.host}/sale`,
    FeedstockUrl: `${Utils.host}/Feedstock`,
    AuditUrl: `${Utils.host}/livestock/biosafety`,
    BILivestockUrl: `${Utils.host}/bi/livestock`,
    PerfUrl: `${Utils.host}/hr/perf`,
    CarcassSaleUrl: `${Utils.host}/pigsltr/carcsale`,
    AuxBizUrl: `${Utils.host}/pigsltr/auxbiz`,
    PartnerSvcUrl: `${Utils.host}/pigsltr/ptsvc`,
    FeedBackUrl: `${Utils.host}/ctnmgt/feedback`,
    PigUrl: `${Utils.host}/livestock/pig`,
    SAPSynUrl: `${Utils.host}/cptvplf/sapsyn`,
    FIARUrl: `${Utils.host}/fi/ar`,
    PigsltrUrl: `${Utils.host}/bi/pigsltr`,
    OtherSynUrl: `${Utils.host}/cptvplf/othersyn`,
};

/** 返回编码后的完整地址 */
Utils.CompleteUrl = function (encodeUrl) {
    return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${encodeUrl.wxid}&redirect_uri=${encodeURIComponent(encodeUrl.url)}&response_type=code&scope=snsapi_base&state=${encodeUrl.sid}#wechat_redirect`;
};
Utils.AjaxError = function (xhr, textStatus, errorThrown) {
    switch (xhr.status) {
        case 401:
            Utils.RemoveSNAuthAT();
            top.location.href = 'https://qas.it.ynsnjt.net/h5it/html/account/basicpage.html'; /* 路径暂时写为绝对路径，适应发布后的环境，开发环境需修改 */
            return;
        case 403:
            let url = 'https://qas.it.ynsnjt.net/h5it/html/components/errors/page403.html';
            if (history.replaceState) {
                history.replaceState(null, document.title, url);
                history.go(0);
            } else {
                location.replace(url);
            }
            return;

        case 429:
            return $.toptip('客户端请求太频繁，请稍后再试。', 'error');

        case 404:
            let _url = 'https://qas.it.ynsnjt.net/h5it/html/components/errors/page404.html';

            if (history.replaceState) {
                history.replaceState(null, document.title, _url);
                history.go(0);
            } else {
                location.replace(_url);
            }
            return;

        // case 400:
        //     if (xhr.responseJSON !== undefined) {
        //         $.toptip(xhr.responseJSON.msg, 'error');
        //     } else {
        //         $.toptip("数据未通过服务校验，请检查数据。", 'error');
        //     }
        //     return;

        case 502:
            $.toptip('服务器异常，请稍后再试，状态码502。', 'error');
            return;

        case 504:
            $.toptip('服务器异常，请稍后再试，状态码504。', 'error');
            return;
        default:
            if (textStatus != 'abort') {
                $.toptip('服务器异常，请联系管理员。', 'error');
                return;
            }
    }
};

Utils.AjaxBeforeSend = function (XMLHttpRequest, textStatus, errorThrow) {
    XMLHttpRequest.setRequestHeader('Authorization', 'Bearer ' + Utils.GetSNAuthAT());
    XMLHttpRequest.setRequestHeader('Content-Type', 'application/json');
    XMLHttpRequest.setRequestHeader('Accept', 'application/json');
};

/* 存入JWT */
Utils.SetSNAuthAT = function (v) {
    return Utils.SetSessionStorage('SNAuthAT', v);
};

Utils.SetRouterState = function (key, value) {
    return Utils.SetSessionStorage(key, value);
};
Utils.GetRouterState = function (key) {
    return Utils.GetSessionStorage(key);
};

/* 获取JWT */

Utils.GetSNAuthAT = function () {
    return Utils.GetSessionStorage('SNAuthAT');
    //return `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aSI6Im9vYmh0IiwidW4iOiLlkajmtqbnjokiLCJ1dCI6IjMyIiwiYXQiOiIyIiwiY291aSI6Im9vY2VrIiwiY291biI6IuWuo-WogeacjeWKoemDqCIsInMiOiJIVE1MIiwidGkiOiJTTkpUIiwibmJmIjoxNzA3MjcxMzMxLCJleHAiOjE3MDcyNzMxMzEsImlhdCI6MTcwNzI3MTMzMSwiaXNzIjoiKiIsImF1ZCI6IioifQ.Lmh2dBi2hIgiyT-e3H_MXW1Br_yffYujHDWSAWb4U14`
};

/**
 * 获取缓存微信用户头像|名字|电话号码
 */
Utils.GetSNWeChat = function () {
    return Utils.GetSessionStorage('SNWeChat');
};
/**
 * 存入 缓存微信用户头像|名字|电话号码
 * @param {*} v
 * @returns
 */
Utils.setSNWeChat = function (v) {
    return Utils.SetSessionStorage('SNWeChat', v);
};

/* 移除JWT */
Utils.RemoveSNAuthAT = function () {
    return window.sessionStorage.removeItem('SNAuthAT');
};
/* 获取URL中的参数
TODO 有缺陷需要完善*/
Utils.GetQueryString = function (name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
};

/* 获取当前时间(从1970.1.1开始的毫秒数)13位 */
Utils.GetTime = function () {
    return new Date().getTime();
};

// Utils.GetTimeMinute = function() {
//     return new Date().getMinutes();
// };

/* 浏览器Web Storage检测 */
Utils.CheckStorageSupport = function () {
    if (!window.sessionStorage) {
        alert('此浏览器不支持sessionStorage');
    }
    if (!window.localStorage) {
        alert('此浏览器不支持localStorage');
    }
};

Utils.GetSessionStorage = function (key) {
    return window.sessionStorage.getItem(key);
};

Utils.GetSessionStorageObj = function (key) {
    return JSON.parse(window.sessionStorage.getItem(key));
};

Utils.SetSessionStorage = function (k, v) {
    if (typeof v == 'object') window.sessionStorage.setItem(k, JSON.stringify(v));
    else window.sessionStorage.setItem(k, v);
};

Utils.SetDateFormat = function (date, format) {
    var o = {
        'M+': date.getMonth() + 1, // month
        'd+': date.getDate(), // day
        'h+': date.getHours(), // hour
        'm+': date.getMinutes(), // minute
        's+': date.getSeconds(), // second
        'q+': Math.floor((date.getMonth() + 3) / 3), // quarter
        S: date.getMilliseconds(),
        // millisecond
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    console.info('SetDateFormat--' + format);
    for (var k in o) {
        if (new RegExp('(' + k + ')').test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
        }
    }
    return format;
};

Utils.GetHMTime = function (strTime, strResult) {
    var result = strResult;
    if (strTime) {
        var cfTime = new Date(strTime);
        var X = cfTime.getHours();
        var H = X > 9 ? X : '0' + X;
        X = cfTime.getMinutes();
        var M = X > 9 ? X : '0' + X;
        result = H + ':' + M;
    }
    return result;
};

Utils.GetNowFormatDate = function (splitstr) {
    var date = new Date();
    var seperator1 = '/';
    if (splitstr) {
        seperator1 = splitstr;
    }
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
};

Utils.NumAdd = function (num1, num2) {
    var baseNum, baseNum1, baseNum2;
    try {
        baseNum1 = num1.toString().split('.')[1].length;
    } catch (e) {
        baseNum1 = 0;
    }
    try {
        baseNum2 = num2.toString().split('.')[1].length;
    } catch (e) {
        baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    var precision = baseNum1 >= baseNum2 ? baseNum1 : baseNum2; //精度
    return ((num1 * baseNum + num2 * baseNum) / baseNum).toFixed(precision);
};

Utils.NumSub = function (num1, num2) {
    var baseNum, baseNum1, baseNum2;
    try {
        baseNum1 = num1.toString().split('.')[1].length;
    } catch (e) {
        baseNum1 = 0;
    }
    try {
        baseNum2 = num2.toString().split('.')[1].length;
    } catch (e) {
        baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    var precision = baseNum1 >= baseNum2 ? baseNum1 : baseNum2;
    return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
};

/*错误提示*/
Utils.Tooltips = function (msg, time = 1500) {
    var $tooltips = $('#topTips');
    $tooltips.text(msg).fadeIn().delay(time).fadeOut();
};

/*
 * toThousands(s,type)
 * 功能：金额按千位逗号分割
 * 参数：s，需要格式化的金额数值.
 * 参数：type,判断格式化后的金额是否需要小数位.传0无小数位，不传或传其他
 *         值保留两位小数
 * 返回：返回格式化后的数值字符串.
 */
Utils.toThousands = (s, type) => {
    if (s == 0.0) {
        s = 0;
    }
    if (/[^[\-|0-9][0-9]*]/.test(s)) return '0';
    if (s == null || s === '') return '';
    s = s.toString().replace(/^(-\d*)$/, '$1.');
    s = s.toString().replace(/^(\d*)$/, '$1.');
    s = (s + '00').replace(/(\d*\.\d\d)\d*/, '$1');
    s = s.replace('.', ',');
    var re = /(\d)(\d{3},)/;
    while (re.test(s)) s = s.replace(re, '$1,$2');
    s = s.replace(/,(\d\d)$/, '.$1');
    if (type == 0) {
        // 不带小数位(默认是有小数位)
        var a = s.split('.');
        if (a[1] == '00') {
            s = a[0];
        }
    }
    return s;
};

Utils.Countdown = (target_date) => {
    let current_date = new Date().getTime();
    let seconds_left = (target_date - current_date) / 1000;
    const _ = function (n) {
        return (n < 10 ? '0' : '') + n;
    };
    if (seconds_left > 0) {
        let days = _(parseInt(seconds_left / 86400));
        seconds_left = seconds_left % 86400;
        let hours = _(parseInt(seconds_left / 3600));
        hours = hours.length > 1 ? hours : `${hours}`;
        seconds_left = seconds_left % 3600;
        let minutes = _(parseInt(seconds_left / 60));
        let seconds = _(parseInt(seconds_left % 60));
        return `<span class="badge sm-rtb-countdown" >${days}</span>&nbsp;天&nbsp;<span class="badge sm-rtb-countdown"> ${hours} </span>&nbsp;时&nbsp;<span class="badge sm-rtb-countdown"> ${minutes} </span>&nbsp;分`;
    } else {
        return `<span class="badge sm-rtb-countdown">00</span>&nbsp;天&nbsp;<span class="badge sm-rtb-countdown">00</span>&nbsp;时&nbsp;<span class="badge sm-rtb-countdown">00</span>&nbsp;分`;
    }
};

Utils.CountdownSeconds = (target_date) => {
    let current_date = new Date().getTime();
    let seconds_left = (target_date - current_date) / 1000;
    const _ = function (n) {
        return (n < 10 ? '0' : '') + n;
    };
    if (seconds_left > 0) {
        let days = _(parseInt(seconds_left / 86400));
        seconds_left = seconds_left % 86400;
        let hours = _(parseInt(seconds_left / 3600));
        hours = hours.length > 1 ? hours : `${hours}`;
        seconds_left = seconds_left % 3600;
        let minutes = _(parseInt(seconds_left / 60));
        let seconds = _(parseInt(seconds_left % 60));
        return `<span class="badge sm-rtb-countdown" >${days}</span>&nbsp;天&nbsp;<span class="badge sm-rtb-countdown"> ${hours} </span>&nbsp;时&nbsp;<span class="badge sm-rtb-countdown"> ${minutes} </span>&nbsp;分&nbsp;<span class="badge sm-rtb-countdown"> ${seconds} </span>&nbsp;秒`;
    } else {
        return `<span class="badge sm-rtb-countdown">00</span>&nbsp;天&nbsp;<span class="badge sm-rtb-countdown">00</span>&nbsp;时&nbsp;<span class="badge sm-rtb-countdown">00</span>&nbsp;分&nbsp;<span class="badge sm-rtb-countdown">00</span>&nbsp;秒`;
    }
};

/**
 * 解析url内容
 * @param {组件 props自带，不需要自定义只需要解构出来，禁止覆盖} location
 * @returns
 */
Utils.ParsingUrl = (location) => {
    if (!location.search) return {};
    let _location = decodeURI(location.search);
    let obj = {};
    let keyValue = [];
    let key = '',
        value = '';
    let paraString = _location.substring(_location.indexOf('?') + 1, _location.length).split('&');
    for (let i in paraString) {
        keyValue = paraString[i].split('=');
        key = keyValue[0];
        value = keyValue[1];
        obj[key] = value;
    }
    return obj;
};
/**
 * 判断数据类型
 * @param {*类型名首字母必须大写} type
 * @param {*传入数据} data
 */
Utils.isType = (type, data) => `[object ${type}]` === Object.prototype.toString.call(data);

/**
 * 判断数据是否不为空
 * @param {*传入数据} data
 */
Utils.IsNotNull = (data) => {
    if (Utils.isType('Array', data)) return data.length > 0 ? true : false;
    if (Utils.isType('Object', data)) return Object.keys(data).length > 0 ? true : false;
    if (Utils.isType('Undefined', data)) return false;
    if (Utils.isType('undefined', data)) return false;
    if (Utils.isType('Null', data)) return false;
    if (Utils.isType('String', data)) {
        if (data.trim() == 'undefined') return false;
        if (data.trim() == 'NAN') return false;
        if (data.trim() == '') return false;
        if (data.trim() == 'null') return false;
        if (data.trim() == 'false') return false;
    }
    if (Utils.isType('Number', data)) {
        if (data == 0) return false;
    }
    if (Utils.isType('boolean', data)) return data;
    return true;
};

/**
 * jsonToUrl
 * @param {*} requestParams
 * @returns
 */
Utils.ConverToUrl = (requestParams) => {
    let params = [];
    Object.entries(requestParams).forEach(([key, value]) => {
        let param = key + '=' + value;
        params.push(param);
    });
    return '?' + params.join('&');
};

/**
 * 节流函数的应用场景：节流是指，在连续的时间内不断触发同个事件，会每隔 n 秒才执行一次这个事件。
 * 常见场景有：懒加载要监听计算滚动条的位置，用户点击提交按钮只允许一定时间内点击一次等等
 * 节流
 * @param {*执行函数} fn
 * @param {*间隔时间} time
 * @returns
 */
Utils.throttle = function (fn, time = 200) {
    let flag = true;
    return function () {
        let self = this;
        let args = [...arguments];
        if (!flag) return;
        flag = false;
        setTimeout(function () {
            fn.apply(self, args);
            flag = true;
        }, time);
    };
};
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S")
Date.prototype.Format = function (fmt) {
    //author: Roy
    var o = {
        'M+': this.getMonth() + 1, //月份
        'd+': this.getDate(), //日
        'h+': this.getHours(), //小时
        'm+': this.getMinutes(), //分
        's+': this.getSeconds(), //秒
        'q+': Math.floor((this.getMonth() + 3) / 3), //季度
        S: this.getMilliseconds(), //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
    return fmt;
};

/**
 * @param {Object} filed 字段名称
 * @param {Object} rev false:正序,true:倒序
 * @param {Object} primer 字段格式化方法，Number等
 */
Utils.SortBy = function (filed, rev, primer) {
    rev = rev ? -1 : 1;
    return function (a, b) {
        a = a[filed];
        b = b[filed];
        if (typeof primer != 'undefined') {
            a = primer(a);
            b = primer(b);
        }
        if (a < b) {
            return rev * -1;
        }
        if (a > b) {
            return rev * 1;
        }
        return 1;
    };
};
